
package com.shiku.imserver.repository.runnable;


import com.mongodb.client.MongoDatabase;
import com.shiku.imserver.common.message.ChatMessage;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class GroupMessageDBRunnable
        extends BaseRepositoryMapRunnable<List<Document>> {
    private MongoDatabase mucMsgDB;
    protected ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private static Logger log = LoggerFactory.getLogger(GroupMessageDBRunnable.class);


    private static final String MUCMsg_ = "mucmsg_";


    public GroupMessageDBRunnable(MongoDatabase mucMsgDB) {

        this.mucMsgDB = mucMsgDB;

    }


    public void putMessageToTask(ChatMessage message) {

        try {

            String roomJid = message.getMessageHead().getTo();

            Document dbObj = new Document();

            try {

                dbObj.put("message", message.toString());

                dbObj.put("room_jid", roomJid);

                dbObj.put("sender_jid", message.getMessageHead().getFrom());

                dbObj.put("sender", message.getFromUserId());

                dbObj.put("ts", Long.valueOf(System.currentTimeMillis()));

                dbObj.put("contentType", Short.valueOf(message.getType()));

                dbObj.put("messageId", message.getMessageHead().getMessageId());

                dbObj.put("timeSend", Long.valueOf(message.getTimeSend()));

                dbObj.put("deleteTime", Long.valueOf(message.getDeleteTime()));

                if (null != message.getContent()) {

                    dbObj.put("content", message.getContent());

                }

            } catch (Exception e) {

                e.printStackTrace();

            }


            try {

                this.lock.writeLock().lock();

                List<Document> list = (List<Document>) this.maps.get(roomJid);

                if (null == list) {
                    list = Collections.synchronizedList(new LinkedList<>());
                }

                list.add(dbObj);

                addMsg(roomJid, list);

            } catch (Exception e) {

                log.error(e.getMessage());

            } finally {

                this.lock.writeLock().unlock();

            }


        } catch (Exception e) {

            e.printStackTrace();

        }

    }


    @Override
    public void runTask() {

        try {

            List<Document> list = null;

            Iterator<Map.Entry<String, List<Document>>> iterator = null;


            iterator = this.maps.entrySet().iterator();

            while (iterator.hasNext()) {

                try {

                    Map.Entry<String, List<Document>> entry = iterator.next();

                    list = entry.getValue();

                    this.lock.writeLock().lock();

                    if (!list.isEmpty()) {

                        this.mucMsgDB.getCollection("mucmsg_" + (String) entry.getKey()).insertMany(list);

                        list.clear();

                    } else {

                        iterator.remove();

                        list = null;

                    }

                } catch (Exception e) {

                    log.error(e.toString(), e);

                } finally {

                    this.lock.writeLock().unlock();

                }

            }

        } catch (Exception e) {

            log.error(e.toString(), e);

        } finally {
        }

    }

}


